package com.example.wifi2;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

public class HistoryContentProvider extends ContentProvider {

    public static final String AUTHORITY = "com.example.wifimanager.provider";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/history");

    // URI匹配常量
    private static final int HISTORY = 1;
    private static final int HISTORY_ID = 2;

    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        uriMatcher.addURI(AUTHORITY, "history", HISTORY);
        uriMatcher.addURI(AUTHORITY, "history/#", HISTORY_ID);
    }

    // 数据库字段
    public static final class HistoryEntry implements BaseColumns {
        public static final String TABLE_NAME = "history";
        public static final String COLUMN_SSID = "ssid";
        public static final String COLUMN_TIMESTAMP = "timestamp";
    }

    private DatabaseHelper dbHelper;

    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    // 创建ContentValues的工具方法
    public static ContentValues createContentValues(String ssid) {
        ContentValues values = new ContentValues();
        values.put(HistoryEntry.COLUMN_SSID, ssid);
        values.put(HistoryEntry.COLUMN_TIMESTAMP, System.currentTimeMillis());
        return values;
    }

    // 查询方法
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor;

        switch (uriMatcher.match(uri)) {
            case HISTORY:
                cursor = db.query(HistoryEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder);
                break;

            case HISTORY_ID:
                String id = uri.getLastPathSegment();
                cursor = db.query(HistoryEntry.TABLE_NAME,
                        projection,
                        BaseColumns._ID + "=?",
                        new String[]{id},
                        null,
                        null,
                        sortOrder);
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    // 插入方法
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (uriMatcher.match(uri) != HISTORY) {
            throw new IllegalArgumentException("Unsupported URI for insertion: " + uri);
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert(HistoryEntry.TABLE_NAME, null, values);

        if (rowId > 0) {
            Uri newUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    // 更新方法
    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;

        switch (uriMatcher.match(uri)) {
            case HISTORY:
                count = db.update(HistoryEntry.TABLE_NAME,
                        values,
                        selection,
                        selectionArgs);
                break;

            case HISTORY_ID:
                String id = uri.getLastPathSegment();
                count = db.update(HistoryEntry.TABLE_NAME,
                        values,
                        BaseColumns._ID + "=?",
                        new String[]{id});
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    // 删除方法
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;

        switch (uriMatcher.match(uri)) {
            case HISTORY:
                count = db.delete(HistoryEntry.TABLE_NAME,
                        selection,
                        selectionArgs);
                break;

            case HISTORY_ID:
                String id = uri.getLastPathSegment();
                count = db.delete(HistoryEntry.TABLE_NAME,
                        BaseColumns._ID + "=?",
                        new String[]{id});
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    // 返回MIME类型
    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case HISTORY:
                return "vnd.android.cursor.dir/vnd.com.example.wifimanager.history";
            case HISTORY_ID:
                return "vnd.android.cursor.item/vnd.com.example.wifimanager.history";
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }

    // 数据库助手类
    private static class DatabaseHelper extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "wifi_history.db";
        private static final int DATABASE_VERSION = 1;

        // 创建表SQL语句
        private static final String SQL_CREATE_ENTRIES =
                "CREATE TABLE " + HistoryEntry.TABLE_NAME + " (" +
                        HistoryEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                        HistoryEntry.COLUMN_SSID + " TEXT NOT NULL," +
                        HistoryEntry.COLUMN_TIMESTAMP + " INTEGER NOT NULL)";

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(SQL_CREATE_ENTRIES);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + HistoryEntry.TABLE_NAME);
            onCreate(db);
        }
    }
}

